/**
 *    @file       threadgroup.cpp
 *
 *    @brief      
 *    @details
 *
 *    @version    1.0
 *    @date       02/11/2014 06:24:59 PM
 *
 *    @author     Theophilus (), wangtf418@gmail.com
 */
#include "threadgroup.h"
#include "server.h"

threadgroup::threadgroup(bf_uint32_t type, bf_uint32_t size, const comargs *args)
	: m_thd_type(type), m_grp_size(size), m_cur_index(0)
{
	if (args)	
	{
		m_args = args->clone();
	}
	else
	{
		m_args = NULL;
	}
}

threadgroup::~threadgroup()
{
	clear();
}

bf_int_t threadgroup::init()
{
	if (m_grp_size == 0)
	{
		return BF_ERROR;
	}

	workthread *thread = NULL;
	bf_int_t ret = 0;
	for (bf_uint32_t i = 0; i < m_grp_size; i ++)
	{
		thread = server::get()->get_classfactory()->gen_workthread(m_thd_type, m_grp_size, i, m_args);
		if (!thread)
		{
			return BF_ERROR;
		}
		ret = thread->start();
		if (ret != BF_OK)
		{
			delete thread;
			return BF_ERROR;
		}
		m_thread.push_back(thread);
	}

	ret = server::get()->register_threadgrp(this);
	if (ret != BF_OK)
	{
		return BF_ERROR;
	}
	return BF_OK;
}

bf_int_t threadgroup::stop_all_thread()
{
	bf_uint32_t threadnum = m_thread.size();
	for (bf_uint32_t i = 0; i < threadnum; i ++)
	{
		if (m_thread[i])
		{
			m_thread[i]->stop();
		}
	}
	return BF_OK;
}

void threadgroup::clear()
{
	if (m_args)
	{
		delete m_args;
		m_args = NULL;
	}

	stop_all_thread();

	bf_uint32_t threadnum = m_thread.size();
	for (bf_uint32_t i = 0; i < threadnum; i ++)
	{
		if (m_thread[i])
		{
			delete m_thread[i];
		}
	}
	m_thread.clear();
}

